import Connection from "mysql2/typings/mysql/lib/Connection";
import fs from "fs";
import mysql from "mysql2";
import mysqlCfg from "../../config/mysql.json";
import path from "path";
import { Application } from "kilom/lib/Application";
import { SvrType } from "../config/SvrCfg";

/**
 * mysql连接池
 */
export let dbPool: mysql.Pool;

/**
 * mysql连接(全局维持一个,不要进行release)
 */
export let db: Connection;

/**
 * 初始化mysql
 */
export async function initMysql(app: Application) {
    if (app.svr.type === SvrType.master) {
        db = mysql.createConnection(mysqlCfg);
        await new Promise(res => {
            db.connect(err => {
                if (err) throw err;
                res(null);
            });
        });
        let sqlLine = '';
        let lines = fs.readFileSync(path.resolve(__dirname, '../../config/kilom_mmo.sql'), 'utf-8').replace(/\\r\\n/g, '\n').split('\n');
        for (let line of lines) {
            sqlLine += line + '\n';
            if (line.includes(';')) {
                let { err } = await querySql(sqlLine);
                if (err) throw err;
                sqlLine = '';
            }
        }
    } else {
        db = mysql.createConnection({
            ...mysqlCfg,
            database: "kilom_mmo",
        });
    }
    dbPool = mysql.createPool({
        ...mysqlCfg,
        database: "kilom_mmo",
        connectionLimit: 100
    });
}


/**
 * Promise包装的sql语句执行
 * @param sql 
 * @param values
 * @param throwErr 是否抛出错误 默认true
 * @returns 
 */
export function querySql(sql: string, values?: any[]): Promise<any>
export function querySql(sql: string, values?: any[], throwErr?: true): Promise<any>
export function querySql(sql: string, values?: any[], throwErr?: false): Promise<{ err?: Error, res?: any }>
export function querySql(sql: string, values?: any[], throwErr = true) {
    return new Promise<any>(async (resolve, reject) => {
        db.query(sql, values, (err, res) => {
            if (err) return throwErr ? reject(err) : resolve({ err });
            resolve(throwErr ? res : { res });
        });
    })
}

/**
 * Promise包装的获取mysql连接
 * @returns 
 */
export function getConn() {
    return new Promise<{ err?: Error, conn?: mysql.Connection }>(res => {
        dbPool.getConnection((err, conn) => {
            if (err) return res({ err });
            res({ conn });
        })
    })
}